/*
 * @Author: 137 '1432417996@qq.com'
 * @Date: 2025-04-07 02:47:01
 * @LastEditors: 137 '1432417996@qq.com'
 * @LastEditTime: 2025-05-16 02:14:04
 * @FilePath: \starter-3\composables\api.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useUserStore } from '@/stores/user'
import { useRuntimeConfig } from '#app'

export const apiCore = (url, options = {}) => {
    const config = useRuntimeConfig()
    console.log('API Base URL:', config.public.apiBaseSsr)
    return useFetch(url, {
        baseURL: config.public.apiBaseSsr || 'https://gotosea123.com/api',
        onRequest({ options }) {
            let token = '';
            token = useUserStore().token;
            options.headers = {
                'Authorization': `Bearer ${token}`,
                ...options.headers,
            }
        },
        onResponse({ response }) {
            console.log('options-------------------------', options)
            console.log('url-------------------------', url)
            console.log('response+++++++++', response)
        },
        ...options
    })
}

export const getApi = (url, options = {}) => {
    // 处理 params 参数
    if (options.params) {
        const params = new URLSearchParams();
        Object.entries(options.params).forEach(([key, value]) => {
            if (value !== undefined && value !== null) {
                params.append(key, value);
            }
        });
        const queryString = params.toString();
        url = `${url}${url.includes('?') ? '&' : '?'}${queryString}`;
        delete options.params;
    }
    return new Promise((resolve, reject) => {
        apiCore(url, {
            ...options,
            method: 'GET'
        }).then(res => {
            resolve(res.data.value);
        }).catch(err => {
            reject(err);
        })
    })
}


export const postApi = (url, options = {}) => {
    // 处理 params 参数
    if (options.params) {
        options.body = options.params;
        delete options.params;
    }
    return new Promise((resolve, reject) => {
        apiCore(url, {
            ...options,
            method: 'post',
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            }
        }).then(res => {
            resolve(res.data.value);
        }).catch(err => {
            reject(err);
        })
    })
}

